package com.fufu.datastructure.stack;

/**
 * 基于数组实现的栈
 * @author: BlcakTiger
 * @date: 2023/2/11 12:44
 * @contact: hsf6661@163.com
 */
public class StackByArray {

    public static void main(String[] args) {
        StackByArray stackByArray = new StackByArray();
        stackByArray.push(12);
        stackByArray.push("金木研");
        stackByArray.push('c');
        stackByArray.push(12.35);
        stackByArray.push(true);
        stackByArray.iterator();
        stackByArray.pop();
        stackByArray.iterator();
    }


    /**
     * stack容器
     * 模拟stack，用于存储数据
     */
    private Object[] stackArr;
    /**
     * 栈顶指针
     * 用于指向栈顶元素
     */
    private int top = -1;

    /**
     * 默认初始化容量为10
     */
    public StackByArray(){
        stackArr = new Object[10];
    }

    /**
     * 添加元素到栈中
     * @param o 被添加的元素
     */
    public void push(Object o){
        if (top==stackArr.length-1){
            throw new RuntimeException("Stack overflow!");
        }
        stackArr[++top] = o;
    }

    /**
     * 出栈
     * @return 返回栈顶元素
     */
    public Object pop(){
        if (top==-1){
            throw new RuntimeException("Stack is empty!");
        }
        return stackArr[top--];
    }

    /**
     * 遍历Stack
     */
    public void iterator(){
        if (top==-1){
            throw new RuntimeException("Stack is empty!");
        }
        System.out.print("[");
        for (int length = top; length >= 0; length--) {
            System.out.print(stackArr[length]+" ");
        }
        System.out.println("]");
    }

}
